/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.config;


import com.comac.ins.common.redis.utils.RedisUtils;
import com.comac.ins.isfd.constant.RedisConstants;
import com.comac.ins.isfd.domain.bomt.IsfdDetailOriginalV2BomVo;
import com.comac.ins.isfd.domain.bomt.IsfdStrengthBomV2InfoVo;
import com.comac.ins.isfd.mapper.BomtStrengthDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.List;


/**
 * 模型管理原始装机清单config
 */
@Slf4j
@Configuration
public class IsfdModelManagementOriginalPartConfig {


    @Autowired
    private BomtStrengthDetailMapper bomtStrengthDetailMapper;


    /**
     * 查询强度数模清单，关联的原始装机清单，返回相关信息
     */
    public List<IsfdDetailOriginalV2BomVo> queryOriginalBomByStrength(String modelNumber, String batchNumber, String sectionNumber, String partNumber) {
        String redisKey = String.join(":", RedisConstants.DETAIL_ORIGINAL_V2_BOM, modelNumber, batchNumber, sectionNumber, partNumber);
        // 两次try catch 的目的是不让redis报错影响流程
        try {
            List<IsfdDetailOriginalV2BomVo> isfdDetailOriginalV2BomVoList = RedisUtils.getCacheObject(redisKey);
            if (!CollectionUtils.isEmpty(isfdDetailOriginalV2BomVoList)) {
                return isfdDetailOriginalV2BomVoList;
            }
        } catch (Exception e) {
            log.error("redis异常", e);
        }

        // 从db拿
        List<IsfdDetailOriginalV2BomVo> fromDB = bomtStrengthDetailMapper.queryOriginalBomByStrength(modelNumber, batchNumber, sectionNumber, partNumber);

        if (CollectionUtils.isEmpty(fromDB) || fromDB.get(0) == null) {
            return null;
        }

        try {
            // 放入redis
            RedisUtils.setCacheObject(redisKey, fromDB, Duration.ofDays(RedisConstants.DETAIL_ORIGINAL_V2_BOM_EXPIRATION_DAY));
        } catch (Exception e) {
            log.error("redis异常", e);
        }
        return fromDB;
    }

    /**
     * 校验机型-批次下是否有导入强度数模清单
     */
    public Boolean checkStrengthBomImport(String modelNumber, String batchNumber) {
        List<IsfdStrengthBomV2InfoVo> isfdStrengthBomV2InfoVos = bomtStrengthDetailMapper.listStrengthByAircraftModelAndTrack(modelNumber, batchNumber);
        if (CollectionUtils.isEmpty(isfdStrengthBomV2InfoVos)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

}
